package com.wf.qfhy.controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wf.qfhy.domain.UserDomain;
import com.wf.qfhy.service.IUserService;
import com.wf.qfhy.utils.QfEncryptUtils;

/**
 * Handles requests for the application home page.
 */
@Controller
public class LoginController {

	@Resource
	private IUserService userService;

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/sys/login";
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/signIn", method = RequestMethod.POST)
	public void signIn(UserDomain userDomain) {
		logger.info("Welcome home! ");
		String username = userDomain.getUserName();
		String passWord = userDomain.getPassWord();
		UsernamePasswordToken token = new UsernamePasswordToken(username, passWord, null);
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.login(token);
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 * 
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public void register(UserDomain userDomain) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		userDomain.setPassWord(QfEncryptUtils.EncoderByMd5(userDomain.getPassWord()));
		userService.saveOrUpdate(userDomain);
	}

}
